package com.solidtrust.app.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.solidtrust.app.SolidtrustConstants;
import com.solidtrust.entity.Client;



public class APIInterceptor extends HandlerInterceptorAdapter{

	private static final Logger log4j = Logger.getLogger(APIInterceptor.class);
	private final Map<String, Client> clientMap = new HashMap<String, Client>();
	
	@PersistenceContext
	private EntityManager em;
	
	@PostConstruct
	public void init(){
		clientMap.clear();
		List<Client> list = em.createQuery("from Client", Client.class).getResultList();
		for (Client c : list) {
			clientMap.put(c.getToken(), c);
		}
	}
	
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object handler) throws Exception {
		log4j.info("start:" + request.getRequestURI());
		String token = request.getParameter(SolidtrustConstants.API_TOKEN);
		if(token != null){
			Client c = clientMap.get(token);
			if(c == null){
				log4j.info("Invalid token: " + token);
			}else{
				if(SolidtrustConstants.MOBILE_IP.equals(c.getIp())){
					return true;
				}
				String ip = request.getRemoteHost();
				StringTokenizer st = new StringTokenizer(c.getIp());
				boolean contains = false;
				while(st.hasMoreTokens()){
					if(ip.equals(st.nextToken())){
						contains = true;
						break;
					}
				}
				if(!contains && !ip.equals(SolidtrustConstants.LOCALHOST)){
					log4j.info("Invalid ip: " + ip);
				}else{
					request.setAttribute(SolidtrustConstants.CLIENT_ID, c.getId());
					return true;
				}
			}
		}else{
			log4j.info("No token");
		}
		response.setStatus(403);
		return false;
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		log4j.info("end:" + request.getRequestURI());
	}
}
